/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package estg.dae.projecto.bank.data;

import estg.dae.projecto.bank.model.Account;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Marco
 * */
@Stateless
public class AccountDao implements AccountDaoLocal {
    @PersistenceContext(unitName="Bank-ejb-PersistenceUnit")
    private EntityManager entityManager;

    public boolean existsNib(String nib){
        Number result = (Number) entityManager.createQuery("SELECT COUNT(a) FROM Account a WHERE a.nib = ?1")
                .setParameter(1, nib)
                .getSingleResult();
        return result.longValue() == 1;
    }
    public boolean existsNumber(long number){
        Number result = (Number)entityManager.createQuery("SELECT COUNT(a) FROM Account a WHERE a.number = ?1")
                .setParameter(1, number)
                .getSingleResult();
        return result.longValue() == 1;
    }

    public Account get(long id) {
        return entityManager.find(Account.class, id);
    }

    public Account getByNib(String nib) {
        return (Account)entityManager.createQuery("SELECT a FROM Account a WHERE a.nib = ?1")
                .setParameter(1, nib)
                .getSingleResult();
    }
    public Account getByNumber(long number) {
        return (Account)entityManager.createQuery("SELECT a FROM Account a WHERE a.number = ?1")
                .setParameter(1, number)
                .getSingleResult();
    }
    public void save(Account account ){
        entityManager.persist(account);
        entityManager.flush();
        entityManager.clear();
    }
    public void update(Account account){
        entityManager.merge(account);
        entityManager.flush();
        entityManager.clear();
    }
    public void delete(Account account){
        entityManager.remove(account);
        entityManager.flush();
        entityManager.clear();
    }
    public Collection<Account> getAll(){
        return entityManager.createQuery("SELECT a FROM Account a").getResultList();
    }
    public Collection<Account> getAll(long clientId){
        return entityManager.createQuery("SELECT a FROM Account a WHERE a.client = ?1")
                .setParameter(1, clientId).getResultList();
    }

    public long getNextAccountNumber(int accountType) {
        try
        {
            long r = (Long)entityManager.createQuery("SELECT MAX(a.number) FROM Account a")
                    .getSingleResult();
            return ((r/100) + 1) * 100 + accountType;
        }
        catch(NullPointerException error)
        {
            return 100 + accountType;
        }
    }
}
